package com.sx.utils;

import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 文件上传工具类
 */
public class FileUploadUtils {

    /**
     * 上传文件
     * @param file 上传的文件
     * @param request HttpServletRequest对象
     * @param uploadPath 上传路径（相对于web根目录）
     * @return 包含文件信息的Map
     * @throws IOException IO异常
     */
    public static Map<String, String> uploadFile(MultipartFile file, HttpServletRequest request, String uploadPath) throws IOException {
        // 获取部署路径
        String realPath = request.getServletContext().getRealPath(uploadPath);
        File dir = new File(realPath);

        // 确保目录存在
        if (!dir.exists()) {
            dir.mkdirs();
        }

        // 获取原文件名
        String originalFilename = file.getOriginalFilename();

        // 处理没有扩展名的文件
        String fileExtension = "";
        if (originalFilename != null && originalFilename.contains(".")) {
            int lastIndexOfDot = originalFilename.lastIndexOf('.');
            if (lastIndexOfDot != -1) {
                fileExtension = originalFilename.substring(lastIndexOfDot);
            }
        }

        // 生成新文件名
        String newFileName = System.currentTimeMillis() + fileExtension;

        // 文件上传路径
        File filePath = new File(realPath, newFileName);
        
        // 保存文件
        file.transferTo(filePath);

        // 返回文件信息
        Map<String, String> resultMap = new HashMap<>();
        resultMap.put("fileName", newFileName);
        resultMap.put("filePath", request.getContextPath() + uploadPath + newFileName);
        
        return resultMap;
    }
    
    /**
     * 上传文件到默认的/upload/路径
     * @param file 上传的文件
     * @param request HttpServletRequest对象
     * @return 包含文件信息的Map
     * @throws IOException IO异常
     */
    public static Map<String, String> uploadFile(MultipartFile file, HttpServletRequest request) throws IOException {
        return uploadFile(file, request, "/upload/");
    }
}